import { reactive, Ref, ref, watch, unref } from "vue";
type RefTypetble<T> = { [P in keyof T]?: Ref<T[P]> | T[P] };
export function useTable<R extends { list: any; total: number }, P>(
  requestApi: (data: P) => PromiseResType<R>,
  queryParms: RefTypetble<P>
) {
  let ListData: Ref<R["list"]> = ref([]);
  //   const keyword = ref("");
  //   const pageNum = ref(1);
  //   const pageSize = ref(10);
  const pageination = reactive({
    total: 0,
    pageNum: 1,
    pageSize: 10,
  });
  const query = {} as P;
  watch(
    () => queryParms,
    (val, oldValue) => {
      console.log(val);
      for (let key in val) {
        if (unref(val[key]))
          query[key] = unref(val[key]) as P[Extract<keyof P, string>];
      }
    },
    { deep: true }
  );
  // 获取用户/姓名分页列表
  async function getAdminList() {
    const res = await requestApi({
      pageNum: pageination.pageNum,
      pageSize: pageination.pageSize,
      ...query,
    });
    if (res.code === 200) {
      ListData.value = res.data.list;
      pageination.total = res.data.total;
    }
  }

  // 首次进入页面时发送请求渲染数据
  getAdminList();
  // // 父传子
  function gethandleSize(val: number) {
    pageination.pageSize = val;
    getAdminList();
  }
  function gethandleCurrent(val: number) {
    pageination.pageNum = val;
    getAdminList();
  }

  return {
    ListData,
    pageination,
    gethandleSize,
    gethandleCurrent,
    getAdminList,
  };
}
